import {getUserTempId} from "@/utils/getUserTempId";
import {reqPostLogin, reqGetUserInfo} from "@/api";

const state = {
	userTempId: getUserTempId(), // 游客账号的唯一ID（标志）
	token: localStorage.getItem('token') || '', // 登录用户初始信息标识
	userInfo: {
		nickName: ''
	}  // 登录用户信息的初始值
};
const mutations = {
	SET_TOKEN_STATE(state, payload) {
		state.token = payload.token
	},
	SET_USERINFO_STATE(state, payload) {
		state.userInfo = payload.userInfo
	},
	DELETE_USERINFO_STATE(state) {
		state.token = ''
		state.userInfo = {nickName: ''}
		localStorage.removeItem('token')
	},
}
const actions = {
	async getToken({commit}, userInfo) {
		try {
			const result = await reqPostLogin(userInfo)
			localStorage.setItem('token', result.token)
			commit('SET_TOKEN_STATE', {token: result.token})
		} catch (e) {
			// alert(e.message)
			return Promise.reject({message: e.message})
			// throw new Error('Error while executing the inner code')
		}
	},
	async getUserInfo({commit}) {
		try {
			const result = await reqGetUserInfo()
			commit('SET_USERINFO_STATE', {userInfo: result})
		} catch (e) {
			return Promise.reject({message: e.message})
		}
	},
	deleteUserInfo({commit}) {
		commit('DELETE_USERINFO_STATE')
	}
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
};